//
//  RegisterViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/24.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "RegisterViewController.h"
#import "PersonalInformationViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "HTSingleTon.h"
@interface RegisterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *ConfirmPassword;
@property (weak, nonatomic) IBOutlet UILabel *warningLable;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *captcha;//验证码
@property (weak, nonatomic) IBOutlet UIButton *timeButton;//获取验证码的按钮
@property (nonatomic, strong) NSTimer *timer1;
@property (weak, nonatomic) IBOutlet UIImageView *touxiang;
@property (nonatomic, strong) UIView *popview;//弹出的view
@end

static int count = 0;

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = YES;
    self.titleLabel.text = @"注册";
    
    UIButton *returnButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    returnButton.frame = CGRectMake(10, 15, 20, 20);
    [returnButton setImage:[UIImage imageNamed:@"return"] forState:(UIControlStateNormal)];
    
    [returnButton addTarget:self action:@selector(doreturn) forControlEvents:(UIControlEventTouchUpInside)];
    [self.topView addSubview:returnButton];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(dochangeIcon:)];
    _touxiang.userInteractionEnabled = YES;
    [self.touxiang addGestureRecognizer:tap];
    
    //设置头像为圆形
    self.touxiang.layer.cornerRadius = 40;
    self.touxiang.layer.masksToBounds = YES;
}

- (void)doreturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

//获取验证码
- (IBAction)gainverificationCode:(id)sender {
    
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneNumber.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        
        if (!error) {
            NSLog(@"block 获取验证码成功");
            
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
          
            _timer1 = timer;
            
        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"codesenderrtitle", nil) message:[NSString stringWithFormat:@"%@",[error.userInfo objectForKey:@"getVerificationCode"]] delegate:self cancelButtonTitle:NSLocalizedString(@"sure", nil) otherButtonTitles:nil, nil];
            
            [alertView show];
        }
    }];
    
}

- (void)updateTime
{
    count++;
    int num = 60 - count;
    NSString *numStr = [NSString stringWithFormat:@"%ds后重发送",num];
    [self.timeButton setTitle:numStr forState:(UIControlStateNormal)];
    
    if (count >= 60) {
        [self.timeButton setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        [_timer1 invalidate];
    }
}


- (IBAction)registerID:(id)sender {

    if ([_name.text isEqualToString:@""] || [_password.text isEqualToString:@""])
    {
        [self p_showAlertView:@"提示" message:@"用户名和密码不能为空"];
        return;
    }
    
    if (NO == [_password.text isEqualToString:_ConfirmPassword.text]) {
        [self p_showAlertView:@"提示" message:@"两次输入的密码不一致"];
        return;
        
    }
    
    [SMSSDK commitVerificationCode:self.captcha.text phoneNumber:_phoneNumber.text zone:@"86" result:^(NSError *error) {
        if (!error) {
            NSLog(@"验证成功");
            
            //注册成功后保存信息到本地
            [[NSUserDefaults standardUserDefaults] setValue:_name.text forKey:@"userName"];
            
            [[NSUserDefaults standardUserDefaults] setValue:_password.text forKey:@"password"];
            
//            [[NSUserDefaults standardUserDefaults] setValue:_touxiang.image forKey:@"touxiang"];
            [self.navigationController popViewControllerAnimated:YES];
            
            
        }else{
            NSLog(@"验证失败");
            _warningLable.text = @"验证码错误";
            return ;
        }
        
    }];
    
}

//选择头像
- (void)dochangeIcon:(UITapGestureRecognizer *)tap
{
    

 
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择从何处选取头像" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self camera];
    }];
    
    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self photo];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alertController addAction:camera];
    [alertController addAction:photos];
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}


- (void)docancel
{
    [_popview removeFromSuperview];
}

- (void)camera
{
    if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备没有摄像头" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}
//打开相册
- (void)photo
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    picker.delegate = self;
    
    picker.allowsEditing = YES;
    
    [self presentViewController:picker animated:YES completion:nil];
    
    [_popview removeFromSuperview];
}

//选中照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImageView *imageView = (UIImageView *)[self.view viewWithTag:5000];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    imageView.image = image;
    
    HTSingleTon *singleTon = [HTSingleTon shareInstance];
    singleTon.iocnPicture.image = image;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//取消相册
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}




//显示提示框
- (void)p_showAlertView:(NSString *)title message:(NSString *)message
{
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
